package com.qd.flow;

import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.valid.group.DefaultGroup;
import com.qd.common.flow.domain.approval.ApprovalDTO;
import com.qd.common.flow.domain.bill.FlowProcessTreeDTO;
import com.qd.flow.service.bill.FlowBillService;
import com.qd.flow.service.bill.FlowHisTaskService;
import com.qd.flow.service.bill.FlowHolderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;

/**
 * 流程/WEB_流程处理
 *
 * @author sjk
 * @create 2024-02-27 15:35
 * @since 1.0.0
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/sys/dataFlow/")
@Slf4j
public class FlowController {
    private final FlowBillService flowBillService;
    private final FlowHisTaskService flowHisTaskService;
    private final FlowHolderService flowHolderService;

    /**
     * 审批
     *
     * @param approvalDTO 审批
     * @return 成功
     */
    @PreAuthorize("@ps.hasPermission('system:dataFlow:approval')")
    @PostMapping(value = "/approval")
    public ApiResultWrapper<Object> approval(@Validated({DefaultGroup.class}) @RequestBody ApprovalDTO approvalDTO) {
        approvalDTO.setApprovalDate(LocalDateTime.now());
        flowHolderService.approval(approvalDTO);
        approvalDTO.freeData();
        return ApiResult.success();
    }

    /**
     * 审批流程树
     *
     * @param billId 审批业务ID
     * @return 成功
     */
    @GetMapping(value = "/processTree")
    public FlowProcessTreeDTO processTree(@Validated @NotBlank(message = "审批业务ID不能为空") String billId) {
        return flowBillService.processTree(billId);
    }

    /**
     * 审批日志
     *
     * @param billId 审批业务ID
     * @return 成功
     */
    @GetMapping(value = "/getFlowHis")
    public ApiResultWrapper<Object> getFlowHis(String billId, String bid) {
        if (!StringUtils.hasLength(billId) && !StringUtils.hasLength(bid)) {
            return ApiResult.error("流程ID和业务ID不能都为空");
        }
        if (StringUtils.hasLength(billId) && StringUtils.hasLength(bid)) {
            return ApiResult.error("流程ID和业务ID只能选择一个");
        }
        if (StringUtils.hasLength(bid)) {
            return ApiResult.success(flowHisTaskService.getListByBid(bid, null));
        }
        if (StringUtils.hasLength(billId)) {
            return ApiResult.success(flowHisTaskService.getListByBillIdDTO(billId));
        }
        return ApiResult.error();
    }

}